#include	<iostream>
#include    <QDebug>
#include    "Board.hpp"

Board*    Board::instance = NULL;

Board::Board()
{
    int mask = 7;
    this->_maskMove.insert(mask, QPair<int,int>(0, 0));
    this->_maskMove.insert(mask << 3, QPair<int,int>(-1, -1));
    this->_maskMove.insert(mask << 6, QPair<int,int>(-1, 0));
    this->_maskMove.insert(mask << 9, QPair<int,int>(-1, 1));
    this->_maskMove.insert(mask << 12, QPair<int,int>(0, 1));
    this->_maskMove.insert(mask << 15, QPair<int,int>(1, 1));
    this->_maskMove.insert(mask << 18, QPair<int,int>(1, 0));
    this->_maskMove.insert(mask << 21, QPair<int,int>(1, -1));
    this->_maskMove.insert(mask << 24, QPair<int,int>(0, -1));



    this->_maskPlace.insert(56,3);
    this->_maskPlace.insert(448,6);
    this->_maskPlace.insert(3584,9);
    this->_maskPlace.insert(28672,12);

    this->_maskPlace.insert(229376,15);
    this->_maskPlace.insert(1835008,18);
    this->_maskPlace.insert(14680064,21);
    this->_maskPlace.insert(117440512,24);


    for (int i = 0 ; i < 19*19 ; ++i)
        this->_board.insert(i, 0);

}

void            Board::display()
{
    std::cout << "\t0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18" << std::endl;

    for (int x = 0 ; x < 19 ; ++x)
    {
        std::cout << std::endl << x << "\t";
        for (int y = 0 ; y < 19 ; ++y)
            std::cout << (instance->getAt(x,y) & 7) << "  ";
    }
    std::cout << std::endl;
    return;
}

Board::~Board()
{}

Board*          Board::getInstance()
{
    if (!Board::instance)
        Board::instance = new Board();
    return instance;
}
QMap<int, int>& Board::getBoard()
{
    return instance->_board;
}
int		Board::getMaskMove(bool pos, int mask)
{
    return !pos ? _maskMove[mask].first : _maskMove[mask].second;
}
int             Board::getMaskPlace(int mask)
{
    return this->_maskPlace[mask];
}
int             Board::getAt(int x, int y)
{
    if (x < 0 || y < 0)
        return -1;
    return instance->_board[x * 19 + y];
}
void            Board::setAt(int modif, int x, int y)
{
    instance->_board[x * 19 + y] = modif;
    return;
}
void            Board::setPlayerAt(int player, int x, int y)
{
    int		newPos;
    int		maskTemp;

    newPos = getAt(x,y);
    maskTemp  = 0x7;
    newPos = (newPos & (~maskTemp)) + player;
    setAt(newPos, x, y);
    for (int mask = 56 ; mask != 939524096 ; mask <<= 3)
    {
        if ((newPos = getAt(x + _maskMove[mask].first,
                       y + _maskMove[mask].second)) < 0)
            continue;
        maskTemp = (mask >= 229376) ? (mask >> 12) : (mask << 12);
        newPos = (newPos & (~maskTemp)) | (player << _maskPlace[maskTemp]);
        setAt(newPos,
              x + _maskMove[mask].first,
              y + _maskMove[mask].second);
    }

}
void            Board::deleteBetween(int pos, const QList<int>& beg)
{
    qDebug("Entree deleteBetween");
    qDebug("Sortie deleteBetween");
}



